import React, { useState, useEffect } from 'react'
import { motion } from 'framer-motion'
import { X, Save, FileText, Check } from 'lucide-react'
import { useMutation, useQuery } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { suiteApi, taskApi } from '../services/api'

const SuiteEditModal = ({ suite, isOpen, onClose, onSuccess }) => {
  const [formData, setFormData] = useState({
    suite_name: '',
    description: '',
    task_files: []
  })

  const isEditing = !!suite

  // 获取所有任务列表
  const { data: availableTasks = [] } = useQuery({
    queryKey: ['tasks'],
    queryFn: () => taskApi.getTasks().then(res => res.data),
    enabled: isOpen
  })

  // 获取套件详情（编辑模式）
  const { data: suiteDetail } = useQuery({
    queryKey: ['suite', suite?.filename],
    queryFn: () => suiteApi.getSuite(suite.filename).then(res => res.data),
    enabled: isEditing && isOpen,
    onSuccess: (data) => {
      setFormData({
        suite_name: data.suite_name || '',
        description: data.description || '',
        task_files: data.tasks?.map(task => task.file?.replace('tasks/', '') || task.file) || []
      })
    }
  })

  // 创建套件
  const createSuiteMutation = useMutation({
    mutationFn: suiteApi.createSuite,
    onSuccess: () => {
      toast.success('套件创建成功')
      onSuccess()
    },
    onError: (error) => {
      toast.error(`创建失败: ${error.response?.data?.detail || error.message}`)
    }
  })

  // 更新套件
  const updateSuiteMutation = useMutation({
    mutationFn: ({ filename, data }) => suiteApi.updateSuite(filename, data),
    onSuccess: () => {
      toast.success('套件更新成功')
      onSuccess()
    },
    onError: (error) => {
      toast.error(`更新失败: ${error.response?.data?.detail || error.message}`)
    }
  })

  // 重置表单
  useEffect(() => {
    if (!isEditing && isOpen) {
      setFormData({
        suite_name: '',
        description: '',
        task_files: []
      })
    }
  }, [isEditing, isOpen])

  const handleInputChange = (field, value) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }))
  }

  const toggleTaskSelection = (taskFilename) => {
    setFormData(prev => ({
      ...prev,
      task_files: prev.task_files.includes(taskFilename)
        ? prev.task_files.filter(f => f !== taskFilename)
        : [...prev.task_files, taskFilename]
    }))
  }

  const selectAllTasks = () => {
    setFormData(prev => ({
      ...prev,
      task_files: availableTasks.map(task => task.filename)
    }))
  }

  const clearAllTasks = () => {
    setFormData(prev => ({
      ...prev,
      task_files: []
    }))
  }

  const handleSubmit = async (e) => {
    e.preventDefault()
    
    if (!formData.suite_name.trim()) {
      toast.error('请输入套件名称')
      return
    }
    
    if (formData.task_files.length === 0) {
      toast.error('请至少选择一个任务')
      return
    }

    const submitData = {
      suite_name: formData.suite_name.trim(),
      description: formData.description.trim(),
      task_files: formData.task_files
    }

    try {
      if (isEditing) {
        await updateSuiteMutation.mutateAsync({
          filename: suite.filename,
          data: submitData
        })
      } else {
        await createSuiteMutation.mutateAsync(submitData)
      }
    } catch (error) {
      console.error('Submit failed:', error)
    }
  }

  if (!isOpen) return null

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4"
      onClick={onClose}
    >
      <motion.div
        initial={{ scale: 0.95, opacity: 0 }}
        animate={{ scale: 1, opacity: 1 }}
        exit={{ scale: 0.95, opacity: 0 }}
        className="bg-white rounded-lg w-full max-w-3xl max-h-[90vh] overflow-hidden"
        onClick={e => e.stopPropagation()}
      >
        {/* 头部 */}
        <div className="flex items-center justify-between p-6 border-b border-gray-200">
          <h2 className="text-xl font-semibold text-gray-900">
            {isEditing ? '编辑套件' : '创建新套件'}
          </h2>
          <button
            onClick={onClose}
            className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* 内容 */}
        <form onSubmit={handleSubmit} className="flex flex-col h-full">
          <div className="flex-1 overflow-y-auto p-6 space-y-6">
            {/* 基本信息 */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  套件名称 *
                </label>
                <input
                  type="text"
                  className="input w-full"
                  value={formData.suite_name}
                  onChange={(e) => handleInputChange('suite_name', e.target.value)}
                  placeholder="输入套件名称"
                  required
                />
              </div>
              
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  描述
                </label>
                <input
                  type="text"
                  className="input w-full"
                  value={formData.description}
                  onChange={(e) => handleInputChange('description', e.target.value)}
                  placeholder="简要描述套件目的"
                />
              </div>
            </div>

            {/* 任务选择 */}
            <div>
              <div className="flex items-center justify-between mb-3">
                <label className="block text-sm font-medium text-gray-700">
                  选择任务文件 * 
                  <span className="text-gray-500 font-normal ml-1">
                    (已选择 {formData.task_files.length} 个)
                  </span>
                </label>
                <div className="flex items-center space-x-2">
                  <button
                    type="button"
                    onClick={selectAllTasks}
                    className="text-sm text-primary-600 hover:text-primary-700"
                    disabled={availableTasks.length === 0}
                  >
                    全选
                  </button>
                  <span className="text-gray-300">|</span>
                  <button
                    type="button"
                    onClick={clearAllTasks}
                    className="text-sm text-gray-600 hover:text-gray-700"
                  >
                    清空
                  </button>
                </div>
              </div>

              {availableTasks.length === 0 ? (
                <div className="text-center py-8 border-2 border-dashed border-gray-300 rounded-lg">
                  <FileText className="w-12 h-12 text-gray-300 mx-auto mb-2" />
                  <p className="text-sm text-gray-500">
                    暂无可用任务，请先创建任务
                  </p>
                </div>
              ) : (
                <div className="border border-gray-200 rounded-lg max-h-80 overflow-y-auto">
                  <div className="divide-y divide-gray-200">
                    {availableTasks.map((task) => (
                      <label
                        key={task.filename}
                        className="flex items-center p-4 hover:bg-gray-50 cursor-pointer"
                      >
                        <div className="relative flex items-center">
                          <input
                            type="checkbox"
                            checked={formData.task_files.includes(task.filename)}
                            onChange={() => toggleTaskSelection(task.filename)}
                            className="h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 rounded"
                          />
                          {formData.task_files.includes(task.filename) && (
                            <Check className="absolute w-3 h-3 text-white pointer-events-none" 
                                  style={{ left: '2px', top: '2px' }} />
                          )}
                        </div>
                        
                        <div className="ml-3 flex-1 min-w-0">
                          <div className="flex items-center space-x-2">
                            <div className="w-2 h-2 bg-blue-500 rounded-full"></div>
                            <span className="text-sm font-medium text-gray-900">
                              {task.name}
                            </span>
                          </div>
                          <p className="text-xs text-gray-500 mt-1">
                            {task.filename}
                          </p>
                        </div>
                      </label>
                    ))}
                  </div>
                </div>
              )}

              {/* 选中任务摘要 */}
              {formData.task_files.length > 0 && (
                <div className="mt-3 p-3 bg-blue-50 border border-blue-200 rounded-lg">
                  <p className="text-sm text-blue-700 mb-2">
                    已选择的任务 ({formData.task_files.length} 个)：
                  </p>
                  <div className="flex flex-wrap gap-1">
                    {formData.task_files.map((filename) => {
                      const task = availableTasks.find(t => t.filename === filename)
                      return (
                        <span
                          key={filename}
                          className="inline-flex items-center px-2 py-1 rounded text-xs bg-blue-100 text-blue-800"
                        >
                          {task?.name || filename}
                        </span>
                      )
                    })}
                  </div>
                </div>
              )}
            </div>
          </div>

          {/* 底部操作 */}
          <div className="flex items-center justify-end space-x-3 p-6 border-t border-gray-200 bg-gray-50">
            <button
              type="button"
              onClick={onClose}
              className="btn-secondary"
            >
              取消
            </button>
            <button
              type="submit"
              disabled={createSuiteMutation.isLoading || updateSuiteMutation.isLoading}
              className="btn-primary disabled:opacity-50"
            >
              {createSuiteMutation.isLoading || updateSuiteMutation.isLoading ? (
                <>
                  <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
                  {isEditing ? '更新中...' : '创建中...'}
                </>
              ) : (
                <>
                  <Save className="w-4 h-4 mr-2" />
                  {isEditing ? '更新套件' : '创建套件'}
                </>
              )}
            </button>
          </div>
        </form>
      </motion.div>
    </motion.div>
  )
}

export default SuiteEditModal